package com.zjt.smart.app;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.multidex.MultiDex;

import com.bumptech.glide.Glide;
import com.bumptech.glide.MemoryCategory;
import com.zjt.smart.dao.DaoMaster;
import com.zjt.smart.dao.DaoSession;
import com.zjt.smart.manager.CacheManager;
import com.zjt.smart.manager.EventManager;
import com.zjt.smart.mvp.model.Event;
import com.zjt.smart.mvp.presenter.base.LoadPresenter;
import com.zjt.smart.observer.EventObserver;
import com.zjt.smart.util.ImageUtil;
import com.zjt.smart.util.LogUtil;
import com.zjt.smart.util.ToastUtil;

/**
 * @author zhengjianting
 * @time 2017/11/2 0002 下午 5:42
 */

public class MainApplication extends Application implements EventObserver {

    public static MainApplication mApp;
    public static CacheManager sCacheManager;
    public static EventManager sEventManager;

    public DaoSession daoSession;
    public SQLiteDatabase db;
    public DbUpgradeHelper helper;
    public DaoMaster daoMaster;

    private GlobalEventHelper eventHelper;

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        initToast();
        UncaughtHandler uncaughtHandler = new UncaughtHandler(this);
        Thread.setDefaultUncaughtExceptionHandler(uncaughtHandler);
        initLogger();
        initDb();
        initImgLoader();
        initCache();
    }

    private void initToast() {
        ToastUtil.register(getApplicationContext());
    }

    private void initLogger() {
        LogUtil.init();
    }

    private void initDb() {
        helper = new DbUpgradeHelper(this, Config.DB_NAME, null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    private void initImgLoader() {
        Glide.get(this).setMemoryCategory(MemoryCategory.NORMAL);
    }

    private void initCache() {
        CacheManager.getInstance().expireCache();
    }

    public static MainApplication getApp() {
        return mApp;
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    public SQLiteDatabase getDb() {
        return db;
    }

    public void exit() {
        onExitApp();
        System.exit(0);
    }

    //每次进入APP时候调用该方法
    public void onLaunchApp() {
        LoadPresenter.isActivate = false;
        eventHelper = new GlobalEventHelper(this);
        EventManager.getInstance().regist(this);
    }

    //每次退出APP时候调用该方法
    public void onExitApp() {
        EventManager.getInstance().unregist(this);
        ImageUtil.clearMemory();
    }

    @Override
    public void onEvent(Event event) {
        eventHelper.handleEvent(event);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
